/*
 * Copyright (C) 2011 Johan Kannala
 *
 * Licensed under the MIT License. You can find a copy of the License at in the
 * license.txt file.
 */
package com.joppe.vocabtutor;

import android.app.Activity;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.*;

/**
 * @author joppe
 *
 */
public class EditWordActivity extends LoggedActivity {
    private static final int NEW_WORD_MENU = 0;
    private static final int NEW_CHAPTER_MENU = 1;
    private static final int CREATE_CHAPTER_REQ = 1;
    
    private VocabTutor mApplication = null;
    private VocabTutorDBHelper mDBHelper = null;
    private LinearLayout mTranslationsContainer = null;
    private Cursor mTranslationCursor = null;
    private Long mBookId = null;
    private Long mChapterId = null;
    private Long mWordId = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = (VocabTutor) this.getApplication();
        mDBHelper = mApplication.getDataHelper();
        readIntentObject();
        setContentView(R.layout.edit_word);
        mTranslationsContainer = (LinearLayout) findViewById(R.id.translations);
        findViewById(R.id.orig_word_fld).requestFocus();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTranslationCursor != null) {
            mTranslationCursor.close();
            mTranslationCursor = null;
        }
    }
    
    @Override
    public void onResume() {
        super.onResume();
        readWordFromDB();
    }
    
    @Override
    public void onStop() {
        super.onStop();
        if (mTranslationCursor != null)
            mTranslationCursor.deactivate();
    }
    
    @Override
    public void onPause() {
        super.onPause();
        TextView wordFld = (TextView) findViewById(R.id.orig_word_fld);
        String text = wordFld.getText().toString();
        if (text.trim().length() > 0)
            saveWordToDB();
    }
    
    @Override
    public void onBackPressed() {
        TextView wordFld = (TextView) findViewById(R.id.orig_word_fld);
        String text = wordFld.getText().toString();
        if (text.trim().length() == 0) {
            deleteWordFromDB();
        }
        Intent result = new Intent();
        result.putExtra("chapter_id", mChapterId.longValue());
        setResult(Activity.RESULT_CANCELED, result);
        finish();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CREATE_CHAPTER_REQ && resultCode == Activity.RESULT_OK) {
            // Create a new word for us to show in the newly create chapter.
            long newWordId = mDBHelper.createNewWord(data.getLongExtra("chapter_id", -1));
            data.putExtra("word_id", newWordId);
            setIntent(data);
            readIntentObject();
            findViewById(R.id.orig_word_fld).requestFocus();
        }
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        readIntentObject();
        findViewById(R.id.orig_word_fld).requestFocus();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, NEW_CHAPTER_MENU, Menu.NONE, "New chapter");
        menu.add(Menu.NONE, NEW_WORD_MENU, Menu.NONE, "New word");
        return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case NEW_CHAPTER_MENU:
            newChapterAction(null);
            return true;
        case NEW_WORD_MENU:
            newWordAction(null);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    private void readIntentObject() {
        Bundle extraInfo = getIntent().getExtras();
        if (extraInfo != null) {
            // Get the book primary key.
            if (extraInfo.containsKey("book_id"))
                mBookId = extraInfo.getLong("book_id");
            else
                throw new IllegalArgumentException("No book id passed to editwordactivity");
            // Get the chapter primary key.            
            if (extraInfo.containsKey("chapter_id"))
                mChapterId = extraInfo.getLong("chapter_id");
            else
                throw new IllegalArgumentException("No chapter id passed to editwordactivity");
            // Get the word primary key, if any.
            Long newWordId;
            if (extraInfo.containsKey("word_id"))
                newWordId = extraInfo.getLong("word_id");
            else
                throw new IllegalArgumentException("No word id passed to editwordactivity");
            // Clear the translation cursor in case this is different from the
            // previous word.
            if (mWordId == null || !mWordId.equals(newWordId)) {
                if (mTranslationCursor != null) {
                    mTranslationCursor.close();
                    mTranslationCursor = null;
                }
            }
            mWordId = newWordId;
        }
        else {
            throw new IllegalArgumentException("No extra info provided to EditWordActivity.");
        }
    }
    
    private void readWordFromDB() {
        TextView bookTitle = (TextView) findViewById(R.id.book_title);
        TextView chapterTitle = (TextView) findViewById(R.id.chapter_title);
        EditText origWord = (EditText) findViewById(R.id.orig_word_fld);
        Cursor c = null;
        try {
            // Fill the headers with data.
            SQLiteDatabase db = mApplication.getDataHelper().getReadableDatabase();
            c = db.query("chapters inner join words on chapters._id = words.chapter_fk inner join books on books._id = chapters.book_fk",
                    new String[] {"books.title", "chapters.title", "words.word", "words.verified"},
                    "words._id = ?", new String[] {Long.toString(mWordId)},
                    null, null, null);
            if (c.moveToFirst()) {
                bookTitle.setText(c.getString(0));
                chapterTitle.setText(c.getString(1));
                origWord.setText(c.getString(2));
            }
            else {
                Log.w("com.joppe.vocabtutor", "Not able to find word with id: "
                        + mWordId);
            }
            // Read the translations from db.
            if (mTranslationCursor == null) {
                mTranslationCursor = db.query("translations", new String[] { "_id", "translation" },
                        "word_fk = ?", new String[] { mWordId.toString() },
                        null, null, null);
            }
            else {
                mTranslationCursor.requery();
            }
            mTranslationsContainer.removeAllViews();
            while (mTranslationCursor.moveToNext()) {
                EditText transFld = addTranslationRow(mTranslationCursor.getLong(0));
                transFld.setText(mTranslationCursor.getString(1));
            }
        }
        catch (Throwable t) {
            t.printStackTrace();
        }
        finally {
            if (c != null)
                c.close();
        }
    }
    
    private EditText addTranslationRow(long transId) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View trans = inflater.inflate(R.layout.edit_word_translation_item,
                mTranslationsContainer, false);
        EditText transFld = (EditText) trans.findViewById(R.id.translation_fld);
        Button deleteBtn = (Button) trans.findViewById(R.id.delete_translation_btn);
        mTranslationsContainer.addView(trans);
        trans.setTag(transId);
        deleteBtn.setTag(R.id.deletable_translation_id, transId);
        return transFld;
    }
    
    private void saveWordToDB() {
        EditText origWord = (EditText) findViewById(R.id.orig_word_fld);
        SQLiteDatabase db = mApplication.getDataHelper().getWritableDatabase();
        ContentValues content = new ContentValues();
        content.put("word", origWord.getText().toString());
        db.update("words", content, "_id = " + mWordId, null);
        int noChildren = mTranslationsContainer.getChildCount();
        for (int childIdx = 0; childIdx < noChildren; childIdx++) {
            ViewGroup transRow = (ViewGroup) mTranslationsContainer
                    .getChildAt(childIdx);
            Long transId = (Long) transRow.getTag();
            EditText transFld = (EditText) transRow
                    .findViewById(R.id.translation_fld);
            String translation = transFld.getText().toString().trim();
            if (translation.length() == 0) {
                db.delete("translations", "_id = ?",
                        new String[] { transId.toString() });
            }
            else {
                content.clear();
                content.put("translation", translation);
                db.update("translations", content, "_id = ?",
                        new String[] { transId.toString() });
            }
        }
    }
    
    private void deleteWordFromDB() {
        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        int noRows = db.delete("words", "_id = ?", new String[] {mWordId.toString()});
        Log.i("com.joppe.vocabtutor", "No rows deleted: " + noRows);
    }
    
    // Event callbacks:
    public void newChapterAction(View view) {
        Intent i = new Intent(this, CreateChapterActivity.class);
        i.putExtra("book_id", mBookId);
        startActivityForResult(i, CREATE_CHAPTER_REQ);
    }
    
    public void newWordAction(View view) {
        saveWordToDB();
        long newWordID = mDBHelper.createNewWord(mChapterId);
        Intent i = new Intent(this, EditWordActivity.class);
        i.putExtra("book_id", mBookId);
        i.putExtra("chapter_id", mChapterId);
        i.putExtra("word_id", newWordID);
        startActivity(i);
    }
    
    public void newTranslation(View button) {
        SQLiteDatabase db = mApplication.getDataHelper().getWritableDatabase();
        ContentValues content = new ContentValues();
        content.put("translation", "");
        content.put("word_fk", mWordId);
        long transId = db.insert("translations", null, content);
        EditText transFld = addTranslationRow(transId);
        transFld.requestFocus();
    }
    
    public void deleteTranslation(View button) {
        SQLiteDatabase db = mApplication.getDataHelper().getWritableDatabase();
        Long transId = (Long) button.getTag(R.id.deletable_translation_id);
        db.delete("translations", "_id = ?", new String[] {transId.toString()});
        View viewToRemove = mTranslationsContainer.findViewWithTag(transId);
        mTranslationsContainer.removeView(viewToRemove);
    }
}
